package bat.iog.hytool.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.charset.StandardCharsets;

public class UDPClient {
    public static void main(String[] args) {
        try {
            // 创建DatagramSocket实例  
            DatagramSocket clientSocket = new DatagramSocket();

            // 设置服务器的IP地址和端口  
            InetAddress serverAddress = InetAddress.getByName("localhost");
            int serverPort = 9876;

            // 准备要发送的消息  
            String message = "Hello from UDP client!";
            byte[] sendData = message.getBytes(StandardCharsets.UTF_8);

            // 创建发送数据的DatagramPacket  
            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, serverAddress, serverPort);

            // 发送数据报  
            clientSocket.send(sendPacket);

            // 创建缓冲区以存储接收到的响应  
            byte[] buffer = new byte[1024];

            // 创建接收响应的DatagramPacket  
            DatagramPacket receivePacket = new DatagramPacket(buffer, buffer.length);

            // 接收响应  
            clientSocket.receive(receivePacket);

            // 转换接收到的字节为字符串  
            String receivedMessage = new String(receivePacket.getData(), 0, receivePacket.getLength(), StandardCharsets.UTF_8);
            System.out.println("Received from server: " + receivedMessage);

            // 关闭客户端的DatagramSocket  
            clientSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}